<template>
  <div ref="chart-mem" style=" width: 90%; height:90% " />
</template>

<script>
import * as echarts from 'echarts'
import { getMemByIp, getMemByIpAndTime } from '@/api/chart'
import { formatDate } from '@/utils/index.js'

export default {
  props: ['ip', 'time'],
  data() {
    return {
      memData: {
        xAxisData: [],
        seriesData: []
      },
      newIp: 'win000k10502',
      newTime: 'day',
      intervalId: null // 存储定时器的ID
    }
  },
  watch: {
    ip(newVal) {
      // 处理 ip 值的变化
      this.updateChart(newVal)
      this.fetchMemData()
    },
    time(newVal) {
      // 处理 time 值的变化
      this.updateChart1(newVal)
      this.fetchCupData()
    }
  },
  mounted() {
    this.fetchMemData()
    this.intervalId = setInterval(this.fetchMemData, 40000)
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }
  },
  methods: {
    formatDate,
    formatDate1(dateString) {
      const date = new Date(dateString);
      const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth() 返回的月份从 0 开始，所以需要加 1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟并补齐两位数
      return `${month}-${day} ${hours}:${minutes}`;
    },
    updateChart(ip) {
      this.newIp = ip
      console.log('ip', ip)
    },
    updateChart1(time) {
      this.newTime = time
    },
    async fetchMemData() {
      const response = await getMemByIpAndTime(this.newIp, this.newTime)
      const mainHost = response
      this.memData.xAxisData = mainHost.map(item => this.formatDate1(item.periodTime))
      this.memData.seriesData = mainHost.map(item => parseFloat(item.avgSys))
      this.createChartMen() // 使用获取到的数据创建图表
      // console.log(this.memData)
    },
    createChartMen() {
      var myChart = echarts.init(this.$refs['chart-mem'])
      var option = {
        title: {
          text: '内存'
        },
        tooltip: {},
        xAxis: {
          axisLabel: {
            // 旋转标签（45度或更多）
            rotate: 30,
            // 格式化函数去掉年份
            formatter: function(value) {
              // 使用正则表达式匹配并去掉年份
              return value.replace(/^\d{4}-/, '')
            }
          },
          data: this.memData.xAxisData,
          name: '日期'
        },
        yAxis: {
          name: '内存利用率',
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: [
          {
            name: '内存利用率',
            type: 'line',
            smooth: true,
            lineStyle: {
              color: '#4BAAF4' // 线的颜色
            },
            itemStyle: {
              color: '#36A8FF' // 折点颜色
            },
            emphasis: {
              areaStyle: {
                color: '#B1DAFA'
              }
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: '#B1DAFA' // 0% 处的颜色B1DAFA
                  },
                  {
                    offset: 1,
                    color: '#F2F9FE' // 100% 处的颜色
                  }
                ],
                false
              )
            },
            data: this.memData.seriesData
          }
        ]
      }
      myChart.setOption(option)
    }
  }
}
</script>

